package com.ews.onlineexchange.service;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.QualificationClass;
import com.ews.onlineexchange.model.Sector;

@Stateless
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public class SectorService {
	
	@Inject
	EntityManager entityManager;	
	
	public Set<Sector> querySectors(String qualificationClassId) {
		if (StringUtils.isBlank(qualificationClassId))
			return new LinkedHashSet<>();
		QualificationClass qc = entityManager.find(QualificationClass.class, qualificationClassId);
		if(qc == null)return  new LinkedHashSet<>();
		else qc.getRootSectors().size();
		return qc.getRootSectors();
	}
	
	@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
	public Sector find(String id) {
		return entityManager.find(Sector.class, id);
	}
	
	private static final String FETCH_CHILD_SECTOR_BY_PARENT_EQL = ""
			+ "	SELECT			sector"
			+ "	FROM			Sector sector "
			+ "	WHERE			sector.parentSector.id = :id	";	
	public List<Sector> getChildSectors(String parentId) {
		Query query = entityManager.createQuery(FETCH_CHILD_SECTOR_BY_PARENT_EQL);
		query.setParameter("id", parentId);
		return query.getResultList();
	}
}
